/*
 * @Author: jiangh1 1141429595@qq.com
 * @Date: 2023-09-18 15:40:12
 * @LastEditors: jiangh1 1141429595@qq.com
 * @LastEditTime: 2023-09-18 15:40:22
 * @FilePath: \note\vue3\frame\vite-ts\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
// import Layout from "../Layout/layout.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("@/views/layout.vue"),
    redirect: "/friends",
    meta: {},
    children: [
      {
        path: "/friends",
        component: () => import("@/views/friends/index.vue"),
        meta: { loginType: true },
      },
      {
        path: "/groups",
        component: () => import("@/views/groups/index.vue"),
        meta: { loginType: true },
      },
    ],
  },
  {
    path: "/login",
    component: () => import("@/views/login/index.vue"),
    meta: { loginType: false },
  },
  {
    path: "/chat",
    component: () => import("@/views/chat/index.vue"),
    meta: { loginType: true },
  },
];

const router = createRouter({
  history: createWebHashHistory(), //createWebHashHistory() hash模式
  routes,
});

router.beforeEach((to: any, from: any, next: any) => {
  if (to.meta.loginType == undefined) {
    window.sessionStorage.clear();
    // router.removeRoute("Layout");
    // 首次登录时弹入登录页
    next({
      path: "/login",
    });
  }
  if (to.meta.loginType) {
    // // 判断是否有地址路由
    // 判断是否有token
    if (sessionStorage.getItem("token") !== null) {
      // 放行路由
      setTimeout(() => next());
    } else {
      window.sessionStorage.clear();
      router.removeRoute("Layout");
      next({
        path: "/login",
      });
    }
  } else {
    window.sessionStorage.clear();
    // router.removeRoute("Layout");
    next();
  }
});
export default router;
